package com.pinyoumei.app.activity.ShoppingCenter.wph;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.TabLayout;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.pinyoumei.app.R;
import com.pinyoumei.app.activity.ShoppingCenter.ShopItemDetailActivity;
import com.pinyoumei.app.activity.ShoppingCenter.ShopSearchActivity;
import com.pinyoumei.app.adapter.WphListAdapter;
import com.pinyoumei.app.bean.ShopCenterMainBean;
import com.pinyoumei.app.bean.ToBaoBean;
import com.pinyoumei.app.bean.WphBean;
import com.pinyoumei.app.fragment.BaseLazyLoadFragment;
import com.pinyoumei.app.network.Constants;
import com.pinyoumei.app.utils.SPUtils;
import com.pinyoumei.app.utils.SignatureUtils;
import com.pinyoumei.app.utils.ToastUtils;
import com.pinyoumei.app.view.LoadingDailog;
import com.pinyoumei.app.view.dialog.ShopRulesDialog;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.google.gson.Gson;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;
import com.lzy.okgo.request.base.Request;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Administrator on 2020-12-14.
 * --------- 日期 ------- 维护人 ------------ 变更内容 --------
 * 2020-12-14        Administrator             新增Person类
 * 2020-12-14        Administrator             增加sex属性
 */
public class WphMainFragment extends BaseLazyLoadFragment implements View.OnClickListener {
//    private Banner banner;
    private List<String> image_list = new ArrayList<>();
    private SmartRefreshLayout swipeRefreshLayout;
    private TabLayout tabPosTab;
    private int page = 1;
    private RecyclerView rv_1;
    private boolean First_Visible = true;
    private Gson gson;
    private LoadingDailog loadingDailog;

    private ShopRulesDialog shopRulesDialog;
    private WphListAdapter wphListAdapter;
    private List<WphBean.ResultBean.GoodsListBean> goods_list = new ArrayList<>();

    private String key_word ="";

    @Override
    public int getLayoutId() {
        return R.layout.fragment_wph_main;
    }


    @Override
    public void initView(View rootView) {
        gson = new Gson();
        LoadingDailog.Builder builder = new LoadingDailog.Builder(getActivity())
                .setMessage("加载中...")
                .setCancelable(true);
        loadingDailog = builder.create();
        swipeRefreshLayout = rootView.findViewById(R.id.swipeRefreshLayout);


        RelativeLayout relative_finish = rootView.findViewById(R.id.relative_finish);
        relative_finish.setOnClickListener(this);

        LinearLayout ll_search = rootView.findViewById(R.id.ll_search);
        ll_search.setOnClickListener(this);

        TextView tv_point = rootView.findViewById(R.id.tv_point);
        tv_point.setOnClickListener(this);
        ImageButton ib_1 = rootView.findViewById(R.id.ib_1);
        ib_1.setOnClickListener(this);
        ImageButton ib_2 = rootView.findViewById(R.id.ib_2);
        ib_2.setOnClickListener(this);


//        banner = rootView.findViewById(R.id.banner);

        swipeRefreshLayout = rootView.findViewById(R.id.swipeRefreshLayout);
        swipeRefreshLayout.setEnableRefresh(false);
//        banner = rootView.findViewById(R.id.banner2);
        tabPosTab = rootView.findViewById(R.id.tab_pos_tab);


        rv_1 = rootView.findViewById(R.id.rv_1);


        tabPosTab.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {


            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                goods_list.clear();

                key_word = (String) tab.getTag();
                SelectedData(key_word);

            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {

            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });


        swipeRefreshLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                page++;


                LoadMoreData( key_word);


                swipeRefreshLayout.finishLoadMore();
            }


        });
        rv_1.setLayoutManager(new StaggeredGridLayoutManager(1, StaggeredGridLayoutManager.VERTICAL));
        wphListAdapter = new WphListAdapter(R.layout.item_shop_wph, null);
        rv_1.setAdapter(wphListAdapter);
        wphListAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                Intent intent = new Intent(getActivity(), ShopItemDetailActivity.class);
                Bundle bundle = new Bundle();
                ShopCenterMainBean.ResultBean.ShowGoodsListBean.GoodsListBean goodsListBean = goods_list.get(position);
                bundle.putString("type","wph");
                bundle.putSerializable("goodsListBean", goodsListBean);
                intent.putExtras(bundle);
                startActivity(intent);

            }
        });

//        EditText et_search = rootView.findViewById(R.id.et_search);
//
//        et_search.setOnEditorActionListener(new TextView.OnEditorActionListener() {
//            @Override
//            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
//                if (actionId == EditorInfo.IME_ACTION_SEARCH) {
//                    //点击搜索的时候隐藏软键盘
//                    hideKeyboard(et_search);
//                    // 在这里写搜索的操作,一般都是网络请求数据
//                    String query_name = et_search.getText().toString().trim();
//                    if (!TextUtils.isEmpty(query_name)) {
//
//                    } else {
//                        Toast.makeText(getActivity(), "请输入问题关键字", Toast.LENGTH_SHORT).show();
//                    }
//                    return true;
//                }
//
//                return false;
//            }
//        });
    }


    @Override
    public void onFragmentVisible() {
        super.onFragmentVisible();
        if (First_Visible) {
            InitData();
        }

    }

    private void InitData() {

        Map<String, Object> map = new HashMap<>();
        map.put("user_id",  SPUtils.getAppUserId(getActivity()));
        map.put("query_type", 1);
        map.put("category_id", "");
        map.put("page", 1);
        map.put("limit", 10);


        OkGo.<String>post(Constants.WPH_INDEX)
                .params("user_id",  SPUtils.getAppUserId(getActivity()))
                .params("query_type", 1)
                .params("category_id", "")
                .params("page", 1)
                .params("limit", 10)
                .params("sign", SignatureUtils.createSignature(map, Constants.SIGN_SECRET))
                .execute(new StringCallback() {


                    private List<WphBean.ResultBean.RoleListBean> role_list;

                    @Override
                    public void onStart(Request<String, ? extends Request> request) {
                        super.onStart(request);
                        loadingDailog.show();
                    }


                    @Override
                    public void onSuccess(Response<String> response) {
                        setData(response);

                    }

                    private void setData(Response<String> response) {
                        First_Visible = false;
                        loadingDailog.dismiss();
                        WphBean wphBean = gson.fromJson(response.body(), WphBean.class);
                        if (wphBean.getCode() >= 0) {
                            //Banner
//                            List<WphBean.ResultBean.TopBannerListBean> top_banner_list = wphBean.getResult().getTop_banner_list();
//                            if (top_banner_list != null && top_banner_list.size() > 0) {
//                                initBanner(top_banner_list);
//                            }
                            //tablaout
                            for (int i = 0; i < wphBean.getResult().getGoods_category_list().size(); i++) {
                                String name = wphBean.getResult().getGoods_category_list().get(i);
                                tabPosTab.addTab(tabPosTab.newTab().setText(name).setTag(name));
                            }
                            //规则
                            role_list = wphBean.getResult().getRole_list();
                            if (role_list!=null && role_list.size()>0){
                                ArrayList<ToBaoBean.ResultBean.RoleListBean> roleListBeans = new ArrayList<>();
                                for (int i = 0; i < role_list.size(); i++) {
                                    ToBaoBean.ResultBean.RoleListBean roleListBean = new ToBaoBean.ResultBean.RoleListBean();
                                    roleListBean.setId(role_list.get(i).getId());
                                    roleListBean.setLevel_name(role_list.get(i).getLevel_name());
                                    roleListBean.setShopping_given_percent(role_list.get(i).getShopping_given_percent());
                                    roleListBeans.add(roleListBean);
                                }
                                shopRulesDialog = new ShopRulesDialog(getActivity(), R.layout.dialog_shop_center_rules, wphBean.getResult().getRole_title(),roleListBeans );

                            }




                        } else {
                            ToastUtils.showShort(wphBean.getMsg());
                        }
                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        loadingDailog.dismiss();
                    }
                });


    }


    private void SelectedData( String key_word) {

        Map<String, Object> map = new HashMap<>();
        map.put("user_id",  SPUtils.getAppUserId(getActivity()));
        map.put("query_type", 2);
        map.put("key_word", key_word);
        map.put("page", 1);
        map.put("limit", 10);


        OkGo.<String>post(Constants.WPH_INDEX)
                .params("user_id",  SPUtils.getAppUserId(getActivity()))
                .params("query_type", 2)
                .params("key_word", key_word)
                .params("page", 1)
                .params("limit", 10)
                .params("sign", SignatureUtils.createSignature(map, Constants.SIGN_SECRET))
                .execute(new StringCallback() {


                    @Override
                    public void onStart(Request<String, ? extends Request> request) {
                        super.onStart(request);
                        loadingDailog.show();
                    }


                    @Override
                    public void onSuccess(Response<String> response) {
                        setData(response);

                    }

                    private void setData(Response<String> response) {
                        loadingDailog.dismiss();
                        WphBean wphBean = gson.fromJson(response.body(), WphBean.class);
                        if (wphBean.getCode() >= 0) {
                            //列表

                            if (wphBean.getResult().getGoods_list() != null && wphBean.getResult().getGoods_list().size() > 0) {
                                //列表
                                goods_list.addAll(wphBean.getResult().getGoods_list());
                                wphListAdapter.setNewData(goods_list);
                            }

                        } else {
                            ToastUtils.showShort(wphBean.getMsg());
                        }
                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        loadingDailog.dismiss();
                    }
                });


    }


    private void LoadMoreData( String key_word) {

        Map<String, Object> map = new HashMap<>();
        map.put("user_id",  SPUtils.getAppUserId(getActivity()));
        map.put("query_type", 2);
        map.put("key_word", key_word);
        map.put("page", page);
        map.put("limit", 10);


        OkGo.<String>post(Constants.WPH_INDEX)
                .params("user_id",  SPUtils.getAppUserId(getActivity()))
                .params("query_type", 2)
                .params("key_word", key_word)
                .params("page", page)
                .params("limit", 10)
                .params("sign", SignatureUtils.createSignature(map, Constants.SIGN_SECRET))
                .execute(new StringCallback() {


                    @Override
                    public void onStart(Request<String, ? extends Request> request) {
                        super.onStart(request);
                        loadingDailog.show();
                    }


                    @Override
                    public void onSuccess(Response<String> response) {
                        setData(response);

                    }

                    private void setData(Response<String> response) {
                        loadingDailog.dismiss();
                        WphBean wphBean = gson.fromJson(response.body(), WphBean.class);
                        if (wphBean.getCode() >= 0) {
                            //列表

                            if (wphBean.getResult().getGoods_list() != null && wphBean.getResult().getGoods_list().size() > 0) {
                                //列表
//                                goods_list.addAll(wphBean.getResult().getGoods_list());
                                wphListAdapter.addData(wphBean.getResult().getGoods_list());
                            }

                        } else {
                            ToastUtils.showShort(wphBean.getMsg());
                        }
                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        loadingDailog.dismiss();
                    }
                });


    }

    /**
     * 隐藏软键盘
     *
     * @param view :一般为EditText
     * @paramcontext :上下文
     */
    public void hideKeyboard(View view) {
        InputMethodManager manager = (InputMethodManager) view.getContext()
                .getSystemService(Context.INPUT_METHOD_SERVICE);
        manager.hideSoftInputFromWindow(view.getWindowToken(), 0);
    }

//    private void initBanner(List<WphBean.ResultBean.TopBannerListBean> banner_list) {
//        //第一个Banner
//        for (int i = 0; i < banner_list.size(); i++) {
//            image_list.add(banner_list.get(i).getImg_path());
//        }
//        if (image_list.size() == 1) {
//            banner.isAutoPlay(false);//设置默认为不轮播
//
//        } else {
//            banner.isAutoPlay(true);//设置默认为自动轮播
//
//        }
//        banner.setBannerStyle(BannerConfig.CIRCLE_INDICATOR);//设置Banner的样式BannerConfig.NUM_INDICATOR
//        banner.setImages(image_list); //存放图片的list集合url
//        banner.setBannerAnimation(Transformer.ZoomOutSlide);//设置Banner轮播的动画特效的样式
//        //banner.setPageTransformer(true,)//自定义轮播动画
//        banner.setImageLoader(new GlideImageLoader());//设置图片加载器
//        banner.setDelayTime(3000);//设置轮播间隔时间
//        //设置指示器位置（当banner模式中有指示器时）
//        banner.setIndicatorGravity(BannerConfig.CENTER);
//        banner.start();
//
//        banner.setOnBannerListener(new OnBannerListener() {
//            @Override
//            public void OnBannerClick(int position) {
//                if (banner_list.get(position).getIs_can_link() == 1) {
//
//                    if (banner_list.get(position).getIs_h5() == 1) {
//                        Intent intent = new Intent(getActivity(), WebViewActivity.class);
//                        intent.putExtra("url", banner_list.get(position).getH5_url());
//                        intent.putExtra("order_title", "");
//                        startActivity(intent);
//                    } else {
//                        //跳转
//                        IntentUtils.Intent_to(getActivity(), banner_list.get(position).getMethod_name());
//                    }
//
//                }
//
//
//            }
//        });
//
//    }
//
//    //使用Glide加载器
//    public class GlideImageLoader extends ImageLoader {
//        @Override
//        public void displayImage(Context context, Object path, ImageView imageView) {
//            //Glide 加载图片
//            RequestOptions placeholder = new RequestOptions().placeholder(R.mipmap.ic_error_loading);
//            String url = path + "";
//            if (url.contains("http")){
//                Glide.with(context).load(path).apply(placeholder).into(imageView);
//            }else{
//                Glide.with(context).load(Constants.MAIN_URL +  path).apply(placeholder).into(imageView);
//            }
//        }
//    }

    @Override
    public void onClick(View v) {
        Intent intent =     new Intent(getActivity(), WphListActivity.class);
        switch (v.getId()) {
            case R.id.relative_finish:
                getActivity().finish();
                break;
            case R.id.tv_point:
                //返佣规则
                shopRulesDialog.show();
                break;

//           :0-超高佣，1-出单爆款
            case R.id.ib_1:
                intent.putExtra("channel_type","0");
                intent.putExtra("title_name","超高佣");
                startActivity(intent);
                break;
            case R.id.ib_2:
                intent.putExtra("channel_type","1");
                intent.putExtra("title_name","出单爆款");
                startActivity(intent);
                break;

            case R.id.ll_search:
                startActivity(new Intent(getActivity(), ShopSearchActivity.class));
                break;


            default:
                break;
        }
    }
}
